package com.fiveflavors.suittar.gui.inputpanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

import com.fiveflavors.suittar.Suittar;
import com.fiveflavors.suittar.SuittarCommand;

public class SuittarStatusUpdateActionListener implements ActionListener,DocumentListener {

	private Suittar suittar = null;
	
	private int commandType = SuittarCommand.COMMAND_UPDATE_STATUS;
	
	public SuittarStatusUpdateActionListener(Suittar suittar,int commandType) {
		this.suittar = suittar;
		this.commandType = commandType;
	}
		
	public void actionPerformed(ActionEvent arg0) {
		update();
	}

	
	public void changedUpdate(DocumentEvent e) {
		checkDocument(e.getDocument());
	}

	public void insertUpdate(DocumentEvent e) {
		checkDocument(e.getDocument());
	}

	public void removeUpdate(DocumentEvent e) {
		checkDocument(e.getDocument());
	}
	
	private void checkDocument(Document doc) {
		try {
			String text = doc.getText(doc.getStartPosition().getOffset(), doc.getLength());
			if (text.indexOf("\n") > -1) {
				update();
			}
		}
		catch(BadLocationException e) {
			e.printStackTrace();
		}
	}

	private void update() {
		SuittarCommand.setCommand(commandType);
		suittar.executeSuittarCommand();		
	}

}
